from django.shortcuts import render
from rest_framework.generics import ListAPIView,GenericAPIView
from rest_framework.mixins import ListModelMixin,CreateModelMixin
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.mail import send_mail

#生成token
import jwt
#验证
import re
#加密模块
import hashlib

import requests

import redis
import string
import random

import datetime
from laboratory.settings import SECRET_KEY
from user.models import *
from .ser import *
#定义ip和端口  
host = "localhost"
port = 6379

#建立链接
r = redis.Redis(host=host,port=port)


#md5加密方法
def make_password(mypass):
	#生成md5对象
	md5 = hashlib.md5()
	#转码操作
	mypass_utf8 = str(mypass).encode(encoding="utf-8")
	#加密操作
	md5.update(mypass_utf8)
	#返回密文
	return md5.hexdigest()
#注册
class RegisterView(APIView):
    def post(self,request):
        email = request.data.get('email')
        print(email)
        password = request.data.get('password')
        print(password)
        verify = request.data.get('verify')
        print(verify)
        code = r.get('code')
        code = code.decode("utf-8")
        print(code)
        if code.lower() != verify.lower():
            return Response({'msg':'验证码不正确',"code":401})
        user = User.objects.filter(email=email).first()
        if user:
            return Response({'code':403,'msg':'用户已存在'})

        #入库
        user = User(email=email,password=make_password(password))
        user.save()

        return Response({'code':200,'msg':'注册成功'})



#登录
class LoginView(APIView):
    def get(self,request):
        email = request.GET.get('email',None)
        password = request.GET.get('password',None)
        user = User.objects.filter(email=email,password=make_password(password)).first()
        if user:
            info = {
                'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=1),
                'uid':user.id,
                'username':user.email,
            }
            token = jwt.encode(info,SECRET_KEY)

            return Response({'code':200,'msg':'登录成功','token':token,'email':user.email})
        else:
            return Response({'code':403,"msg":'登录失败'})



#三方登录 微博

class WeiboView(APIView):
    def get(self,request):
        #获取传递来的code
        code = request.GET.get('code')
        data = {
            'client_id':'230424959',
            'client_secret':'c0dd7c309449aef36c97a4fc7251e19b',
            'grant_type':'authorization_code',
            'code':code,
            'redirect_uri':'http://127.0.0.1:8080/weibo',
        }
        r = requests.post('https://api.weibo.com/oauth2/access_token',data=data)
        uid = r.json().get('uid')
        if not uid:
            return Response({'msg':'微博登录失败'},status=401)
        # access_token = r.json()['access_token']

        #保存 微博账号到  open_users中  ger_or_create 先去查找 查找到了就返回，查找不对就添加
        open_user = OpenUser.objects.filter(uid=uid).first()
        if not open_user:
            #数据表中不存在，则插入第三方账号
            OpenUser.objects.create(uid=uid,type=1)
            return Response({'msg':'登录成功','code':202,'uid':uid})  # code 202 表示 还需要进一步让用户绑定账号

        return Response({"msg": "登录成功",'code':200})

    def post(self,request):
        #处理微博账号绑定本地账号
        email = request.data.get('email','')
        print(email)
        password = request.data.get('password','')
        uid = request.data.get('uid','')
        print(uid)
        #先去查询本地的用户
        user = User.objects.filter(email=email,password=make_password(password)).first()
        if user:
            OpenUser.objects.filter(uid=uid).update(user_id=user.id)
            return Response({'msg':'绑定成功','code':200})
        else:
            return Response({'msg':'本地账号不存在，请重新绑定','code':400})



    

# 邮箱验证接口
class Verify_Code(APIView):
    def post(self,request):
        email = request.data.get('email','')
        if email:
            words = random.sample(string.digits+string.ascii_letters,6)
            words = "".join(words)
            r.set('code',words)
            r.expire('code',60)
            #邮箱信息填写
            send_mail(subject="实验室", message="", from_email="405025815@qq.com",
            recipient_list=['',email],html_message="验证码:%s"% words)

            return Response({'msg':'验证码以发送请查收','code':200})
    
        else:
            return Response({'msg':'验证失败'})


# class CenterView(APIView):
#     def get(self,request):
#         id = request.GET.get('id')
#         queryset = User.objects.filter(id=id)
#         ser = UserSer(queryset,many=True)
#         return Response(ser.data)

# class CourseView(APIView):
#     def get(self,request):
#         queryset = Coures.objects.all()
#         ser = UserSer(queryset,many=True)
#         return Response(ser.data)

class CourseView(APIView):
    def get(self,request):
        queryset = Laber.objects.all()
        ser = LaberSer(queryset,many=True)
        return Response(ser.data)

class Show_idol(APIView):
    def post(self,request):
        idol = request.data.get('idol')
        queryset = UserDeng.objects.filter(idol__fans__name=idol)
        print(idol)
        ser = UserSer(queryset,many=True)
        return Response(ser.data)

#重置密码
class Send_Email(APIView):
    def post(self, request):
        email = request.data.get('email')
        # if re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email):
        user = User.objects.filter(email=email).first()
        if user:
            send_mail(
                subject='实验楼重置密码邮件',
                message='实验楼重置密码！！！',
                from_email='405025815@qq.com',
                recipient_list=[email],
                html_message='<a href="http://127.0.0.1:8080/Resetting_password?email={}">点击链接重置密码</a>'.format(email)
            )
            return Response({'coed': 200, 'message': '重置密码邮件发送成功'})
        else:
            return Response({'code': 501, 'message': '该用户不存在，请确认邮箱是否正确'})
        # else:
        #     return Response({'code': 409, 'message': '输入邮箱格式不正确'})

# 重置密码
class Resetting_Password(APIView):
    def post(self, request):
        passwd1 = request.data.get('password1')
        passwd2 = request.data.get('password2')
        email = request.data.get('email')
        print(passwd1,passwd2)
        if passwd1 == passwd2:
            User.objects.filter(email=email).update(password=passwd1)
            return Response({'code': 200, 'message': '密码重置成功'})
        else:
            return Response({'code': 503, 'message': '两次密码不一致'})


class Show_fans(APIView):
    def post(self,request):
        fans = request.data.get('fans')
        print(fans)
        queryset = UserDeng.objects.filter(fans__idol__name=fans)
        ser = UserSer(queryset,many=True)
        return Response(ser.data)

# class ShowView(ListModelMixin,GenericAPIView):
#     queryset = UserDeng.objects.all()
#     serializer_class = UserSer
#     def get(self,request):
#         return self.list(request)